package steed.netty.serialization;

import java.io.ByteArrayOutputStream;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufOutputStream;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import steed.netty.server.NettyServerBootstrap;
import steed.util.base.BaseUtil;

public class JsonEncoder extends ChannelOutboundHandlerAdapter {

	@Override
	public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
		byte[] bytes = (BaseUtil.getJson(msg) + NettyServerBootstrap.delimiter).getBytes();
		ByteBuf out = ctx.alloc().buffer(bytes.length);
		ByteBufOutputStream bout = new ByteBufOutputStream(out);
		ByteArrayOutputStream oout = new ByteArrayOutputStream(bytes.length);
		try {
			oout.write(bytes);
			oout.writeTo(bout);
			oout.flush();
			bout.flush();
		} finally {
			if (oout != null) {
				oout.close();
			} else {
				bout.close();
			}
		}

		ctx.write(out, promise);// (1)
	}

}
